package com.xls.pet.service.impl;

import com.xls.pet.entity.Category;
import com.xls.pet.mapper.CategoryMapper;
import com.xls.pet.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<Category> tree() {
        List<Category> categoryList = categoryMapper.selectAll();
        return categoryList.stream()
                .filter(category -> Objects.isNull(category.getParentId()))
                .peek(category -> category.setChildCategoryList(getChildCategoryList(category, categoryList)))
                .collect(Collectors.toList());

    }

    public List<Category> getChildCategoryList(Category parent, List<Category> categoryList) {
        List<Category> list = categoryList.stream()
                .filter(category -> Objects.nonNull(category.getParentId()) && category.getParentId().equals(parent.getId()))
                .peek(category -> category.setChildCategoryList(getChildCategoryList(category, categoryList)))
                .sorted(Comparator.comparing(Category::getId))
                .collect(Collectors.toList());
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }
}
